package org.Lin.server;

import org.Lin.util.AESUtil;
import org.Lin.util.DatabaseUtil;
import org.json.JSONObject;
import java.sql.*;

public class LoginServer {

    public static void handle(JSONObject json) {
        String userID = json.getString("userID");
        String passwordHash = json.getString("password");

        try (Connection conn = DatabaseUtil.getConnection()) {
            String sql = "SELECT * FROM User WHERE userID = ? AND password = ?";
            PreparedStatement stmt = conn.prepareStatement(sql);
            stmt.setString(1, userID);
            stmt.setString(2, passwordHash);

            ResultSet rs = stmt.executeQuery();
            if (rs.next()) {
                JSONObject response = new JSONObject();
                response.put("type", "login_success");
                response.put("userID", userID);
                response.put("name", rs.getString("name"));
                response.put("email", rs.getString("email"));

                // 更新最后登录时间
                String updateSql = "UPDATE User SET last_login = NOW() WHERE userID = ?";
                PreparedStatement updateStmt = conn.prepareStatement(updateSql);
                updateStmt.setString(1, userID);
                updateStmt.executeUpdate();

                NetworkServer.send(AESUtil.encrypt(response.toString()));
            } else {
                JSONObject error = new JSONObject();
                error.put("type", "login_failed");
                error.put("message", "用户ID或密码错误");
                NetworkServer.send(AESUtil.encrypt(error.toString()));
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}
